<template>
  <div class="p-2">
    <!-- OTA版本管理模块 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="版本名称" prop="versionName">
          <el-input
            v-model="queryParams.versionName"
            placeholder="请输入版本名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="queryParams.deviceType" placeholder="设备类型" clearable style="width: 150px">
            <el-option label="传感器" value="sensor" />
            <el-option label="控制器" value="controller" />
            <el-option label="网关" value="gateway" />
            <el-option label="摄像头" value="camera" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本状态" prop="versionStatus">
          <el-select v-model="queryParams.versionStatus" placeholder="版本状态" clearable style="width: 150px">
            <el-option label="开发中" value="developing" />
            <el-option label="测试中" value="testing" />
            <el-option label="已发布" value="released" />
            <el-option label="已下线" value="deprecated" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
            v-model="queryParams.releaseTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="10" style="margin-bottom: 8px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalVersions }}</div>
            <div class="stat-label">总版本数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value developing">{{ statistics.developingVersions }}</div>
            <div class="stat-label">开发中</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value released">{{ statistics.releasedVersions }}</div>
            <div class="stat-label">已发布</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value testing">{{ statistics.testingVersions }}</div>
            <div class="stat-label">测试中</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新建版本</el-button>
          <el-button type="success" plain icon="Upload" @click="handleBatchUpload">批量上传</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport">导出版本</el-button>
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除</el-button>
        </div>
        <div class="toolbar-right">
          <el-button type="info" plain icon="Refresh" @click="handleRefresh">刷新</el-button>
          <el-button type="primary" plain icon="Setting" @click="handleSettings">版本设置</el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="versionList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="版本ID" prop="versionId" width="120" align="center" />
        <el-table-column label="版本名称" prop="versionName" width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">{{ scope.row.versionName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="版本号" prop="versionNumber" width="120" align="center">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.versionNumber }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" prop="deviceType" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getDeviceTypeTagType(scope.row.deviceType)">{{ getDeviceTypeText(scope.row.deviceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" prop="fileSize" width="100" align="center">
          <template #default="scope">
            <span>{{ formatFileSize(scope.row.fileSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="versionStatus" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.versionStatus)">{{ getStatusText(scope.row.versionStatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="升级设备数" prop="upgradeCount" width="120" align="center">
          <template #default="scope">
            <el-link type="primary" @click="handleViewUpgradeDevices(scope.row)">{{ scope.row.upgradeCount }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="成功率" prop="successRate" width="100" align="center">
          <template #default="scope">
            <span :class="{ 'text-green-500': scope.row.successRate >= 90, 'text-red-500': scope.row.successRate < 70 }">
              {{ scope.row.successRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="发布人" prop="publisher" width="120" align="center" />
        <el-table-column label="发布时间" prop="releaseTime" width="160" align="center" />
        <el-table-column label="操作" width="320" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" plain size="small" icon="View" @click="handleView(scope.row)">详情</el-button>
            <el-button type="success" plain size="small" icon="Edit" @click="handleEdit(scope.row)" v-if="scope.row.versionStatus === 'developing'">编辑</el-button>
            <el-button type="warning" plain size="small" icon="Upload" @click="handlePublish(scope.row)" v-if="scope.row.versionStatus === 'testing'">发布</el-button>
            <el-button type="info" plain size="small" icon="Download" @click="handleDownload(scope.row)">下载</el-button>
            <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑版本对话框 -->
    <VersionFormDialog
      v-model:visible="dialog.visible"
      :title="dialog.title"
      :form-data="form"
      :rules="rules"
      @submit="handleSubmit"
      @cancel="cancel"
    />

    <!-- 版本详情对话框 -->
    <VersionDetailDialog
      v-model:visible="detailDialog.visible"
      :detail-data="detailData"
      :upgrade-stats="upgradeStats"
    />

    <!-- 升级设备列表对话框 -->
    <UpgradeDevicesDialog
      v-model:visible="upgradeDevicesDialog.visible"
      :upgrade-devices-list="upgradeDevicesList"
      @refresh="handleRefreshUpgradeDevices"
    />

    <!-- 批量上传对话框 -->
    <BatchUploadDialog
      v-model:visible="batchUploadDialog.visible"
      @submit="handleBatchUploadSubmit"
      @cancel="handleBatchUploadCancel"
    />
  </div>
</template>

<script setup name="VersionManage" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Upload, Download, Delete, View, Edit, Setting, UploadFilled } from '@element-plus/icons-vue'
import VersionFormDialog from './components/VersionFormDialog.vue'
import VersionDetailDialog from './components/VersionDetailDialog.vue'
import UpgradeDevicesDialog from './components/UpgradeDevicesDialog.vue'
import BatchUploadDialog from './components/BatchUploadDialog.vue'

// 响应式数据
const loading = ref(false)
const total = ref(0)
const multipleSelection = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  versionName: '',
  deviceType: '',
  versionStatus: '',
  releaseTime: null
})

// 统计数据
const statistics = reactive({
  totalVersions: 156,
  developingVersions: 23,
  releasedVersions: 89,
  testingVersions: 44
})

// 版本列表
const versionList = ref([
  {
    versionId: 'V001',
    versionName: '传感器固件v2.1.0',
    versionNumber: 'v2.1.0',
    deviceType: 'sensor',
    fileSize: 2048576,
    versionStatus: 'released',
    upgradeCount: 156,
    successRate: 95.5,
    publisher: '张三',
    releaseTime: '2024-01-15 10:30:00',
    description: '修复温度读取精度问题，优化功耗管理',
    changelog: '1. 修复温度传感器读取精度问题\n2. 优化低功耗模式\n3. 增加自诊断功能',
    forceUpgrade: false,
    upgradeTimeout: 300
  },
  {
    versionId: 'V002',
    versionName: '网关固件v1.5.2',
    versionNumber: 'v1.5.2',
    deviceType: 'gateway',
    fileSize: 8388608,
    versionStatus: 'testing',
    upgradeCount: 12,
    successRate: 83.3,
    publisher: '李四',
    releaseTime: '2024-01-14 14:20:00',
    description: '增加MQTT协议支持，提升数据传输稳定性',
    changelog: '1. 新增MQTT协议支持\n2. 优化数据传输算法\n3. 修复内存泄漏问题',
    forceUpgrade: true,
    upgradeTimeout: 600
  },
  {
    versionId: 'V003',
    versionName: '控制器固件v3.0.1',
    versionNumber: 'v3.0.1',
    deviceType: 'controller',
    fileSize: 4194304,
    versionStatus: 'developing',
    upgradeCount: 0,
    successRate: 0,
    publisher: '王五',
    releaseTime: '',
    description: '重构控制逻辑，增加远程配置功能',
    changelog: '1. 重构控制算法\n2. 增加远程配置接口\n3. 优化响应速度',
    forceUpgrade: false,
    upgradeTimeout: 450
  },
  {
    versionId: 'V004',
    versionName: '摄像头固件v1.2.3',
    versionNumber: 'v1.2.3',
    deviceType: 'camera',
    fileSize: 16777216,
    versionStatus: 'released',
    upgradeCount: 89,
    successRate: 98.9,
    publisher: '赵六',
    releaseTime: '2024-01-13 09:15:00',
    description: '提升图像质量，增加夜视功能',
    changelog: '1. 优化图像处理算法\n2. 增加红外夜视功能\n3. 修复录像文件损坏问题',
    forceUpgrade: false,
    upgradeTimeout: 900
  },
  {
    versionId: 'V005',
    versionName: '传感器固件v2.0.5',
    versionNumber: 'v2.0.5',
    deviceType: 'sensor',
    fileSize: 1572864,
    versionStatus: 'deprecated',
    upgradeCount: 234,
    successRate: 92.3,
    publisher: '孙七',
    releaseTime: '2024-01-10 16:45:00',
    description: '旧版本固件，已停止维护',
    changelog: '1. 基础功能实现\n2. 初版发布',
    forceUpgrade: false,
    upgradeTimeout: 300
  }
])

// 升级统计数据
const upgradeStats = reactive({
  total: 156,
  success: 149,
  failed: 3,
  pending: 4
})

// 升级设备列表
const upgradeDevicesList = ref([
  {
    deviceId: 'DEV001',
    deviceName: '温度传感器01',
    currentVersion: 'v2.0.5',
    targetVersion: 'v2.1.0',
    upgradeStatus: 'success',
    progress: 100,
    startTime: '2024-01-15 10:30:00',
    endTime: '2024-01-15 10:35:20',
    errorMessage: ''
  },
  {
    deviceId: 'DEV002',
    deviceName: '温度传感器02',
    currentVersion: 'v2.0.5',
    targetVersion: 'v2.1.0',
    upgradeStatus: 'failed',
    progress: 45,
    startTime: '2024-01-15 10:30:00',
    endTime: '2024-01-15 10:33:15',
    errorMessage: '网络连接超时'
  },
  {
    deviceId: 'DEV003',
    deviceName: '温度传感器03',
    currentVersion: 'v2.0.5',
    targetVersion: 'v2.1.0',
    upgradeStatus: 'upgrading',
    progress: 78,
    startTime: '2024-01-15 10:32:00',
    endTime: '',
    errorMessage: ''
  },
  {
    deviceId: 'DEV004',
    deviceName: '温度传感器04',
    currentVersion: 'v2.0.5',
    targetVersion: 'v2.1.0',
    upgradeStatus: 'pending',
    progress: 0,
    startTime: '',
    endTime: '',
    errorMessage: ''
  }
])

// 对话框状态
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false
})

const upgradeDevicesDialog = reactive({
  visible: false
})

const batchUploadDialog = reactive({
  visible: false
})

// 表单数据
const form = reactive({
  versionId: '',
  versionName: '',
  versionNumber: '',
  deviceType: '',
  versionStatus: 'developing',
  description: '',
  changelog: '',
  forceUpgrade: false,
  upgradeTimeout: 300
})

// 详情数据
const detailData = reactive({})

// 表单验证规则
const rules = {
  versionName: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
  versionNumber: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  versionStatus: [{ required: true, message: '请选择版本状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入版本描述', trigger: 'blur' }]
}

// 获取设备类型标签类型
const getDeviceTypeTagType = (type: string) => {
  const typeMap = {
    sensor: 'primary',
    controller: 'success',
    gateway: 'warning',
    camera: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取设备类型文本
const getDeviceTypeText = (type: string) => {
  const typeMap = {
    sensor: '传感器',
    controller: '控制器',
    gateway: '网关',
    camera: '摄像头'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    developing: 'info',
    testing: 'warning',
    released: 'success',
    deprecated: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    developing: '开发中',
    testing: '测试中',
    released: '已发布',
    deprecated: '已下线'
  }
  return statusMap[status] || status
}

// 获取升级状态标签类型
const getUpgradeStatusTagType = (status: string) => {
  const statusMap = {
    pending: 'info',
    upgrading: 'warning',
    success: 'success',
    failed: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取升级状态文本
const getUpgradeStatusText = (status: string) => {
  const statusMap = {
    pending: '待升级',
    upgrading: '升级中',
    success: '成功',
    failed: '失败'
  }
  return statusMap[status] || status
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 查询
const handleQuery = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    versionName: '',
    deviceType: '',
    versionStatus: '',
    releaseTime: null
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialog.title = '新建版本'
  dialog.visible = true
  Object.assign(form, {
    versionId: '',
    versionName: '',
    versionNumber: '',
    deviceType: '',
    versionStatus: 'developing',
    description: '',
    changelog: '',
    forceUpgrade: false,
    upgradeTimeout: 300
  })
  fileList.value = []
}

// 编辑
const handleEdit = (row: any) => {
  dialog.title = '编辑版本'
  dialog.visible = true
  Object.assign(form, row)
  fileList.value = []
}

// 查看详情
const handleView = (row: any) => {
  Object.assign(detailData, row)
  detailDialog.visible = true
}

// 查看升级设备
const handleViewUpgradeDevices = (row: any) => {
  upgradeDevicesDialog.visible = true
}

// 发布版本
const handlePublish = (row: any) => {
  ElMessageBox.confirm(`确认发布版本"${row.versionName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('版本发布成功')
    handleQuery()
  })
}

// 下载版本
const handleDownload = (row: any) => {
  ElMessage.success(`正在下载版本：${row.versionName}`)
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除版本"${row.versionName}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    handleQuery()
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm('确认删除选中的版本？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
    handleQuery()
  })
}

// 批量上传
const handleBatchUpload = () => {
  batchUploadDialog.visible = true
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 刷新
const handleRefresh = () => {
  handleQuery()
}

// 版本设置
const handleSettings = () => {
  ElMessage.info('版本设置功能开发中')
}



// 提交表单
const handleSubmit = () => {
  ElMessage.success('版本保存成功')
  dialog.visible = false
  handleQuery()
}

// 批量上传提交
const handleBatchUploadSubmit = (fileList: any[]) => {
  ElMessage.success(`批量上传${fileList.length}个版本成功`)
  batchUploadDialog.visible = false
  handleQuery()
}

// 批量上传取消
const handleBatchUploadCancel = () => {
  batchUploadDialog.visible = false
}

// 刷新升级设备列表
const handleRefreshUpgradeDevices = () => {
  ElMessage.success('升级设备列表已刷新')
  // 这里可以添加实际的刷新逻辑
}

// 选择变更
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  handleQuery()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  handleQuery()
}

// 组件挂载
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-value.developing {
  color: #909399;
}

.stat-value.released {
  color: #67c23a;
}

.stat-value.testing {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.changelog-content {
  white-space: pre-line;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
}

.upgrade-stat {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.upgrade-stat.success {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
}

.upgrade-stat.failed {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
}

.upgrade-stat.pending {
  background-color: #fdf6ec;
  border: 1px solid #e6a23c;
}

.upgrade-stat .stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.upgrade-stat.success .stat-number {
  color: #67c23a;
}

.upgrade-stat.failed .stat-number {
  color: #f56c6c;
}

.upgrade-stat.pending .stat-number {
  color: #e6a23c;
}

.upgrade-stat .stat-label {
  font-size: 12px;
  color: #909399;
}

.text-green-500 {
  color: #67c23a;
}

.text-red-500 {
  color: #f56c6c;
}

.upload-demo {
  width: 100%;
}
</style>